package com.ruihu.admin.module.business.tasknode.service;

import com.ruihu.admin.common.constant.JudgeEnum;
import com.ruihu.admin.module.business.log.interfacelog.dao.InterfaceLogDao;
import com.ruihu.admin.module.business.log.interfacelog.domain.dto.InterfaceLogDTO;
import com.ruihu.admin.module.business.log.interfacelog.domain.dto.InterfaceLogQueryDTO;
import com.ruihu.admin.module.business.log.interfacelog.domain.entity.InterfaceLogEntity;
import com.ruihu.admin.module.support.task.service.AIImageDyTask;
import com.ruihu.admin.module.support.task.service.DyTaskService;
import com.ruihu.admin.module.system.systemconfig.SystemConfigService;
import com.ruihu.admin.module.system.systemconfig.constant.SystemConfigEnum;
import com.ruihu.admin.module.system.systemconfig.domain.dto.SystemConfigDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * AI自动任务
 */
@Service
@Slf4j
public class AIInterfaceAutoRunner implements ApplicationRunner {

    @Autowired
    private InterfaceLogDao interfaceLogDao;

    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private DyTaskService dyTaskService;


    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 查询所有状态为未完成的AI图片接受任务
        InterfaceLogQueryDTO queryDTO = new InterfaceLogQueryDTO();
        queryDTO.setStatus(JudgeEnum.NO.getValue().toString());
        List<InterfaceLogEntity> interfaceLogEntityList = this.interfaceLogDao.queryList(queryDTO);
        if (interfaceLogEntityList.size() > 0) {
            String cronExpression = "0/5 * * * * ?";
            SystemConfigDTO systemConfigDTO = this.systemConfigService.getCacheByKey(SystemConfigEnum.Key.AI_INTERFACE_POLL_CRON);
            if (Objects.nonNull(systemConfigDTO)) {
                cronExpression = systemConfigDTO.getConfigValue();
            }

            log.info("start to execute ai task");
            for (InterfaceLogEntity interfaceLogEntity : interfaceLogEntityList) {
                this.dyTaskService.scheduleTask(interfaceLogEntity.getId(), new AIImageDyTask(interfaceLogEntity), cronExpression);
            }
            log.info("execute ai task end");
        }
    }
}
